<template>
  <!-- 页面-值集管理 -->
  <div 
    :class="{'innerPageTable-box-OneTwo': !useTableSearchBar}"
    class=" value-set-list-wrap innerPageTable-out-flex">
    <!-- 搜索区域 -->
    <SelfAdaption v-if="!useTableSearchBar">
      <Form
        :model="searchForm"
        ref="vsForm"
        slot="adaption-bar"
        label-position="top"
        class="ivu-form-no-margin-bottom"
        inline
      >
        <!-- 值集编码 -->
        <Form-item prop="vsCode" :label="$t('module.valueSet.vsCode')">
          <Input
            type="text"
            v-model.trim="searchForm.vsCode"
            :placeholder="$t('module.valueSet.enterVsCode')"
            @on-enter="searchValueSet"
          ></Input>
        </Form-item>

        <!-- 值集名称 -->
        <Form-item prop="vsName" :label="$t('module.valueSet.vsName')">
          <Input
            type="text"
            v-model.trim="searchForm.vsName"
            :placeholder="$t('module.valueSet.enterVsName')"
            @on-enter="searchValueSet"
          ></Input>
        </Form-item>

        <!-- 查询\重置按钮 -->
        <Form-item prop="button" class="search-solt-btn">
          <RPButton optType="search" @click="searchValueSet" />
          <RPButton optType="reset" @click="resetValueSet" />
        </Form-item>
      </Form>
    </SelfAdaption>
    <InnerPageTable ref="valueSetTable" :config="pageTableConfig">
      <!-- table bar 添加-->
      <div slot="table-bar">
        <!--<OptionRight resourceCode="items_add">-->
        <RPButton optType="create" @click="addOrupdateValueSet" />
        <!--</OptionRight>-->
        <!--<OptionRight resourceCode="dict_item_del">-->
        <!-- <Button icon="trash-a" @click="deleteValueSet">{{$t("common.delete")}}</Button> -->
        <!--</OptionRight>-->
      </div>

      <Form
        :model="searchForm"
        ref="vsForm"
        slot="table-search-bar"
        v-if="useTableSearchBar"
        label-position="top"
        class="ivu-form-no-margin-bottom"
        inline
      >
        <!-- 值集编码 -->
        <Form-item prop="vsCode">
          <Input
            type="text"
            v-model.trim="searchForm.vsCode"
            :placeholder="$t('module.valueSet.enterVsCode')"
            clearable
            @on-enter="searchValueSet"
            @on-blur="searchValueSet"
            @on-clear="searchValueSet"
          ></Input>
        </Form-item>

        <!-- 值集名称 -->
        <Form-item prop="vsName">
          <Input
            type="text"
            v-model.trim="searchForm.vsName"
            :placeholder="$t('module.valueSet.enterVsName')"
            clearable
            @on-enter="searchValueSet"
            @on-blur="searchValueSet"
            @on-clear="searchValueSet"
          ></Input>
        </Form-item>
      </Form>
    </InnerPageTable>
  </div>
</template>
<script>
// import OptionRight from "../../../components/OptionRight.vue";
import AddOrUpdateValueSet from "./AddOrUpdateValueSet.vue";
import VDefineSelf from "./VDefineSelf.vue";
import role from "@lang/modules/role";
import valueSet from "@lang/modules/valueSet";
import { ComTypes, CoreModuleName } from "@/const.js";
import tenantAPI from "@/api/tenantApi.js";

export default {
  name: "value-set",
  components: {
    // OptionRight: OptionRight
  },
  locales: {
    "zh-CN": {
      module: {
        role: role["zh-CN"],
        valueSet: valueSet["zh-CN"]
      }
    },
    "en-US": {
      module: {
        role: role["en-US"],
        valueSet: valueSet["en-US"]
      }
    }
  },
  data() {
    const vm = this;
    const { userInfo } = $store.state[CoreModuleName];
    return {
      title: "值集管理",
      valuesetRest: true,
      valuesetRest: true,
      currTenantCode: userInfo.tenantCode || "", //租户编码
      currTenantName: "", //租户名称
      searchForm: {
        adminId: "",
        productCode: "",
        tenantCode: "",
        vsCode: "",
        vsName: ""
      },
      isRipples: false, //判断是平台登录还是租户登录
      roleList: [],
      pageTableConfig: {
        loadDataFn: this.GetValueSetList,
        columnsFn: this.columns,
        autoFirst: false, //默认 就是 false, 要配置在这里
        rowClassNameFn: this.rowClassName // 自定义行样式
      }
    };
  },
  computed: {},
  created: function () {
    this.initCurrentRole();
    this.QueryProductData();
    this.getTenantCode(); //判断是否是平台登录
    this.initTenant(); //获取租户编码对应的租户名称
  },
  beforeMount: function () {},
  mounted: function () {
    this.searchValueSet();
  },
  beforeDestroy: function () {},
  destroyed: function () {},
  methods: {
    // 初始化所属租户,获取租户编码对应的租户名称
    initTenant() {
      tenantAPI.queryAllTenantList().then(data => {
        for (const tenant of data) {
          if (this.currTenantCode == tenant.tenantCode) {
            this.currTenantName = tenant.tenantName;
          }
        }
      });
    },
    // 自定义行样式
    rowClassName(row) {
      //showAsh:1为置灰 0 为不变
      if (row.showAsh == 1) {
        return "tableDisableStyle";
      }
    },
    GetValueSetList({ responseProcess, param }) {
      // console.log(param);
      $http.post(`${window.RPConfig.setting}/valueset/list/page`, param).then(response => {
        responseProcess(response.data);
      });
    },
    columns() {
      const COLUMN_WIDTH = window.RPConfig.COLUMN_WIDTH
      return [
        // {
        //   title: this.$t("common.num"),
        //   type: "index",
        //   width: 50,
        //   align: "center"
        // },

        {
          title: this.$t("module.valueSet.vsCode"),
          align: "left",
          key: "vsCode",
          minWidth: 150,
          sortable: true
        },
        {
          title: this.$t("module.valueSet.vsName"),
          align: "left",
          key: "vsName",
          minWidth: 150,
          sortable: true
        },

        {
          title: this.$t("module.valueSet.vsType"),
          align: "center",
          key: "vsType",
          minWidth: COLUMN_WIDTH.COLUMN_WIDTH_4_WORDS,
          maxWidth: COLUMN_WIDTH.COLUMN_WIDTH_4_WORDS + COLUMN_WIDTH.MAX_WIDTH_MORE,

          render: (h, params) => {
            return h(
              "span",
              params.row.vsType == "1" ? this.$t("module.valueSet.independent") : this.$t("module.valueSet.subordinate")
            );
          }
        },

        // {
        //   title: this.$t("module.valueSet.isPublic"),
        //    align: "left",
        //   key: "publicFlag",
        //   width: 80,
        //   render: (h, params) => {
        //     return h(
        //       "span",
        //       params.row.publicFlag == "1" ? this.$t("module.valueSet.public") : this.$t("module.valueSet.notpublic")
        //     );
        //   }
        // },
        {
          title: this.$t("module.valueSet.vsValueSource"),
          align: "center",
          key: "vsValueSource",
          minWidth: COLUMN_WIDTH.COLUMN_WIDTH_5_WORDS,
          maxWidth: COLUMN_WIDTH.COLUMN_WIDTH_5_WORDS + COLUMN_WIDTH.MAX_WIDTH_MORE,
          render: (h, params) => {
            return h("span", this.getValueSourceName(params.row.vsValueSource));
          }
        },
        {
          title: this.$t("module.valueSet.ownnerTenant"),
          align: "left",
          key: "tenantName",
          minWidth: 150,
          // render: (h, params) => {
          //   return h("span", this.getProductName(params.row.tenantName));
          // }
        },
        {
          title: this.$t("common.status"),
          align: "center",
          key: "enabled",
          minWidth: 80,
          maxWidth: 80 + COLUMN_WIDTH.MAX_WIDTH_MORE,
          render: (h, params) => {
            return h(
              "StatusButton",
              {
                // 修改StatusButton内容居中
                style: {
                  "justify-content": "center"
                },
                props: {
                  status: params.row.enabled == 1 ? "0" : "1"
                }
              },
              params.row.enabled == 1 ? this.$t("common.enable") : this.$t("common.disable")
            );
          }
        },
        {
          title: this.$t("common.operating"),
          align: "left",
          fixed: "right",
          width: 100,
          // render: (h, params) => {
          //   return this.getRenderContent(h, params);
          // },
          render: (h, params) => {
            return h("RowTools", {
              props: {
                data: this.getOperatingCols(params.row)
              }
            });
          }
        }
      ];
    },
    getOperatingCols(row) {
      let isClick = true;
      let operatingCols = [];

      // 如果是平台层
      if (this.currTenantCode == window.RPConfig.rootTenantCode) {
        if (row.source == 2) {
          operatingCols.push({
            type: "icon",
            icon: "md-create",
            text: this.$t("common.edit"),
            handle: () => {
              this.edit(row.id, row.version);
            }
          });
          operatingCols.push({
            type: "icon",
            icon: "ios-settings",
            text: this.$t("module.valueSet.vsDefine"),
            handle: () => {
              this.valueDefine(row, true);
            }
          });
          operatingCols.push({
            type: "icon",
            icon: "ios-trash",
            text: this.$t("common.delete"),
            hidden: row.enabled == 1 ? true : false,
            handle: () => {
              this.deleted(row.id);
            }
          });
        } else {
          operatingCols.push({
            type: "icon",
            icon: "ios-settings",
            text: this.$t("module.valueSet.vsDefine"),
            handle: () => {
              this.valueDefine(row, true);
            }
          });
        }
      }
      // 如果是租户层
      if (this.currTenantCode != window.RPConfig.rootTenantCode) {
        // 如果是平台建的
        if (row.tenantId == window.RPConfig.rootTenantCode) {
          operatingCols.push({
            type: "icon",
            icon: "ios-settings",
            text: this.$t("module.valueSet.vsDefine"),
            handle: () => {
              this.valueDefine(row, true);
            }
          });
        } else {
          // 如果是租户建的
          if (row.source == 2) {
            operatingCols.push({
              type: "icon",
              icon: "md-create",
              text: this.$t("common.edit"),
              handle: () => {
                this.edit(row.id, row.version);
              }
            });
            if (row.vsValueSource != 4) {
              operatingCols.push({
                type: "icon",
                icon: "ios-settings",
                text: this.$t("module.valueSet.vsDefine"),
                handle: () => {
                  this.valueDefine(row, true);
                }
              });
            }
            if (row.enabled == 0) {
              operatingCols.push({
                type: "icon",
                icon: "ios-trash",
                text: this.$t("common.delete"),
                handle: () => {
                  this.deleted(row.id);
                }
              });
            }
          }
        }
      }

      return operatingCols;
    },
    
    edit(id, version) {
      new this.$pageModal(
        AddOrUpdateValueSet,
        {
          props: {
            vsId: id,
            version: version,
            adminProductId: this.searchForm.productCode,
            ownnerTenantCode: this.currTenantCode,
            ownnerTenantName: this.currTenantName,
            isRipples: this.isRipples
          }
        },
        data => {
          data && this.searchValueSet(this.$refs.valueSetTable.param.pageNum);
        }
      );
    },

    searchValueSet(page = 1) {
      this.$refs["valueSetTable"].load(this.searchForm, page);
    },
    resetValueSet() {
      this.$refs["vsForm"].resetFields();
      this.searchValueSet();
    },
    // getProductName(code) {
    //   for (let item of this.products) {
    //     if (code == item.vsiKey) {
    //       return item.vsiValue;
    //     }
    //   }
    //   return code;
    // },
    // 判断是平台登录还是用户登录
    getTenantCode() {
      this.isRipples = this.currTenantCode == window.RPConfig.rootTenantCode ? true : false;
    },
    // 初始化当前角色
    initCurrentRole() {
      let { userInfo } = this.$store.state[CoreModuleName];
      // 根据当前岗位查询数据
      this.searchForm.productCode = ""; // currentRole.productId; 2.0 中没有产品的概念
      this.searchForm.tenantCode = userInfo.tenantCode;
    },
    QueryProductData() {
      //获取产品类型
      $http
        .get(`${window.RPConfig.setting}/valueset/item/list?vsCode=RC_PRODUCT`)
        .then(response => {
          this.products = response.data;
          // this.searchValueSet();
        })
        .catch(error => {
          this.$message.error({
            content: error.message,
            duration: 3
          });
        });
    },
    addOrupdateValueSet(obj, page) {
      new this.$pageModal(
        AddOrUpdateValueSet,
        {
          props: {
            vsId: obj.id,
            version: obj.version,
            adminProductId: this.searchForm.productCode,
            ownnerTenantCode: this.currTenantCode,
            ownnerTenantName: this.currTenantName,
            isRipples: this.isRipples
          }
        },
        data => {
          data && this.searchValueSet(page);
        }
      );
    },
    deleted(id) {
      new $confirm(this.$t("common.warning.confirmToDelete"), this).then(() => {
        $http.post(`${window.RPConfig.setting}/valueset/delete`, [id]).then(() => {
          this.$message.success({
            content: this.$t("common.deleteSuccess"),
            duration: 3
          });
          this.searchValueSet();
        });
      });
    },
    valueDefine(vDefine, isEdit = false) {
      new this.$sidelipPage(
        VDefineSelf,
        {
          props: {
            vsType: vDefine.vsType,
            isEdit: isEdit,
            vsId: vDefine.id,
            vsCode: vDefine.vsCode,
            columnType: vDefine.vsType,
            tenantCode: this.searchForm.tenantCode,
            vsValueSource: vDefine.vsValueSource,
            ownnerTenant: this.currTenantCode,
            tenantId: vDefine.tenantId,
            source: vDefine.source
          }
        },
        data => {
          this.searchValueSet(this.$refs.valueSetTable.param.pageNum);
        }
      );
    },
    deleteValueSet() {
      let deleteStr = this.getIdAndVersion();
      if (deleteStr == "") {
        this.$message.error({
          content: this.$t("module.valueSet.selestItems"),
          duration: 3
        });
        return;
      }
      new $confirm(`${this.$t("common.confirmDeletion")}`, this).then(() => {
        $http.post(`${window.RPConfig.setting}/valueset/delete`, this.getIdAndVersion()).then(() => {
          this.$message.success({
            content: this.$t("module.valueSet.deleteSuccessfully"),
            duration: 3
          });
          this.searchValueSet();
        });
      });
    },
    getIdAndVersion() {
      let list = this.$refs["valueSetTable"].getSelectioned() || [];
      let ids = [];
      for (let vs of list) {
        ids.push(vs.id);
      }
      return ids;
    },
    getValueSourceName(key) {
      if (key == 1) {
        return this.$t("module.valueSet.valueSourceItem.system");
      } else if (key == 2) {
        return this.$t("module.valueSet.valueSourceItem.scalable");
      } else if (key == 3) {
        return this.$t("module.valueSet.valueSourceItem.custom");
      } else if (key == 4) {
        return this.$t("module.valueSet.valueSourceItem.dynamic");
      }
      return key;
    }
  },
  watch: {},
  directives: {}
};
</script>
<style lang="less">
.Status-dot i[data-v-1cec71cc],
.Status-dot span[data-v-1cec71cc] {
  -webkit-transform: translate(-50%, -50%);
}
</style>
